package com.theunderminejournal.updater;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * This class is responsible for getting a fresh copy of TUJ Addon using the provided URL.
 * This file is then downloaded and the MarketData.lua file is extracted to the existing MarketData.lua.
 * 
 * 
 *
 */
public class TUJMarketData {

	private final int BUFFER = 2048;

	public void updateMarketData(File localMarketDataFile, String url) {
		InputStream in = null;

		try {
			in = this.getTUJAddon(url);

			this.extractMarketData(in, localMarketDataFile);
		} catch (Exception e1) {
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}

	}

	
	private InputStream getTUJAddon(String url) {

		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);
		InputStream instream = null;

		try {
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				instream = entity.getContent();
			}
		} catch (ClientProtocolException e) {
		} catch (IllegalStateException e) {
		} catch (IOException e) {
		}

		return instream;
	}

	private void extractMarketData(InputStream stream, File outputFile) {

		ZipInputStream zis = null;
		BufferedOutputStream dest = null;

		try {

			dest = new BufferedOutputStream(new FileOutputStream(outputFile));
			zis = new ZipInputStream(new BufferedInputStream(stream));
			ZipEntry entry;
			while ((entry = zis.getNextEntry()) != null) {
				if (entry.getName().equals("TheUndermineJournal/MarketData.lua")) {
					int count;
					byte data[] = new byte[BUFFER];
					// write the files to the disk
					while ((count = zis.read(data, 0, BUFFER)) != -1) {
						dest.write(data, 0, count);
					}
					dest.flush();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (zis != null)
				try {
					zis.close();
				} catch (IOException e) {
					// Do nothing
				}

			if (dest != null)
				try {
					dest.close();
				} catch (IOException e) {

				}
		}

	}
}
